package com.example.demo.finitestatemachine.machine;

import com.example.demo.finitestatemachine.event.LiftEvent;
import com.example.demo.finitestatemachine.state.LiftState;
import com.example.demo.finitestatemachine.state.LiftStateCodeEnums;
import com.example.demo.finitestatemachine.transition.AbstractLiftTransition;

import java.util.List;

/**
 * @author liyuncong
 * @version 1.0
 * @file LiftAbstractStateMachine
 * @brief LiftAbstractStateMachine
 * @details LiftAbstractStateMachine
 * @date 2022-12-28
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                        NAME               DESCRIPTION
 * 2022-12-28                  liyuncong          Created
 */
public abstract class LiftAbstractStateMachine {

    private static List<LiftState> allStates = null;

    /**
     * 状态机执行事件
     *
     * @param stateCode 当前状态
     * @param event     当前事件
     * @return 下一个状态
     */
    public LiftState execute(LiftStateCodeEnums stateCode, LiftEvent event) {
        final LiftState state = this.getState(stateCode);
        for (AbstractLiftTransition transition : state.getTransitions()) {
            if (event.getEventCode() == transition.getEventCode()) {
                return transition.execute(event);
            }
        }
        return null;
    }

    public LiftState getState(LiftStateCodeEnums stateCode) {
        if (allStates == null) {
            allStates = this.declareAllStates();
        }
        for (LiftState state : allStates) {
            if (state.getStateCode() == stateCode) {
                return state;
            }
        }
        return null;
    }

    public abstract List<LiftState> declareAllStates();
}
